package com.aizhixin.lab.company.controller;

import com.aizhixin.lab.account.dto.AccountDTO;
import com.aizhixin.lab.account.service.AccountService;
import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.PageData;
import com.aizhixin.lab.common.core.UserInforCore;
import com.aizhixin.lab.common.utils.TokenUtil;
import com.aizhixin.lab.company.domain.AccountDomain;
import com.aizhixin.lab.company.domain.QueryUserDomain;
import com.aizhixin.lab.company.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jxl.read.biff.BiffException;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/base/user")
@Api(value = "用户管理相关API")
public class UserController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private UserService userService;


    @RequestMapping(value = "/getUserByToken", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "根据token查询用户信息,role角色包括:superadmin,admin,teacher,student;deleteFlag状态标识：0-正常，2-停用", response = Void.class, notes = "根据token查询用户信息<br>@author hsh")
    public ResponseEntity<?> getUserByToken(@RequestHeader("Authorization") String token) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        return new ResponseEntity(account, HttpStatus.OK);
    }

    @RequestMapping(value = "/delete", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "DELETE", value = "删除用户", response = Void.class, notes = "删除用户<br>@author hsh")
    public ResponseEntity<?> deleteUser(@RequestHeader("Authorization") String token,
                                        @ApiParam(value = "userId", required = false) @RequestParam(value = "userId", required = false) Long userId,
                                        @ApiParam(value = "role角色分为：admin,teacher,student", required = false) @RequestParam(value = "role", required = false) String role,
                                        @ApiParam(value = "批量删除使用userIds参数", required = false) @RequestParam(value = "userIds", required = false) List<Long> userIds) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        Map<String, Object> result = null;
        if (null != userIds && !userIds.isEmpty()) {
            result = userService.deleteAll(userIds, role);
        } else {
            result = userService.delete(userId);
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/updatePassword", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "PUT", value = "修改密码", response = Void.class, notes = "修改密码<br>@author hsh")
    public ResponseEntity<?> updatePassword(@RequestHeader("Authorization") String token,
                                            @ApiParam(value = "userId", required = false) @RequestParam(value = "userId", required = false) Long userId,
                                            @ApiParam(value = "password", required = false) @RequestParam(value = "password", required = false) String password,
                                            @ApiParam(value = "newPassword", required = false) @RequestParam(value = "newPassword", required = false) String newPassword) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        Map<String, Object> result = userService.updatePassword(userId, password, newPassword);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/resetPassword", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "重置密码", response = Void.class, notes = "重置密码<br>@author hsh")
    public ResponseEntity<?> resetPassword(@RequestHeader("Authorization") String token,
                                           @ApiParam(value = "userId", required = false) @RequestParam(value = "userId", required = false) Long userId) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        Map<String, Object> result = userService.resetPassword(userId);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/adduser", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "注册用户", response = Void.class, notes = "注册用户（无token验证）<br>@author zhengning")
    public ResponseEntity<?> addUser(
            @ApiParam(value = "jobNum:学号/工号（老师学生必填），collegeId:院系id（老师学生必填），professionalId(专业id)和classId(班级id)为学生必填，角色分为：teacher,student,账号默认密码为dingli123", required = false) @RequestBody AccountDTO dto) {

        if (StringUtils.isEmpty(dto.getRole())) {
            Map<String, Object> result = new HashMap<>();
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "注册用户信息缺少角色！");
        } else {
            if (StringUtils.isEmpty(dto.getJobNum())) {
                Map<String, Object> result = new HashMap<>();
                result.put(ApiReturnConstants.SUCCESS, false);
                result.put(ApiReturnConstants.ERROR, "注册学生/老师账号信息缺少学号/工号！");
            }
            if (dto.getRole().equals(UserInforCore.ROLE_TEACHER)) {
                dto.setUserName("tea" + dto.getJobNum());
            }
            if (dto.getRole().equals(UserInforCore.ROLE_STUDENT)) {
                dto.setUserName("stu" + dto.getJobNum());
            }
        }
        Map<String, Object> result = userService.addAccount(dto);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/createuser", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "新建用户", response = Void.class, notes = "新建用户<br>@author zhengning")
    public ResponseEntity<?> createUser(@RequestHeader("Authorization") String token,
                                        @ApiParam(value = "jobNum:学号/工号（老师学生必填），collegeId:院系id（老师学生必填），professionalId(专业id)和classId(班级id)为学生必填，username:账号（管理员必填），角色分为：admin,teacher,student,账号默认密码为dingli123", required = false) @RequestBody AccountDTO dto) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        if (StringUtils.isEmpty(dto.getRole())) {
            Map<String, Object> result = new HashMap<>();
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "注册用户信息缺少角色！");
        } else {
            if (StringUtils.isEmpty(dto.getJobNum())) {
                Map<String, Object> result = new HashMap<>();
                result.put(ApiReturnConstants.SUCCESS, false);
                result.put(ApiReturnConstants.ERROR, "注册学生/老师账号信息缺少学号/工号！");
            }
            if (dto.getRole().equals(UserInforCore.ROLE_TEACHER)) {
                dto.setUserName("tea" + dto.getJobNum());
            }
            if (dto.getRole().equals(UserInforCore.ROLE_STUDENT)) {
                dto.setUserName("stu" + dto.getJobNum());
            }
        }
        Map<String, Object> result = userService.addAccount(dto);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/createuserList", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "批量添加学生", response = Void.class, notes = "新建用户<br>@author lwq")
    public ResponseEntity<?> createuserList(@RequestHeader("Authorization") String token,
                                            @ApiParam(value = "collegeId:院系id，professionalId(专业id)和classId(班级id)必填", required = false)AccountDTO dto,
                                            @ApiParam(value = "Excel数据文件", required = true) @RequestParam(value = "file") MultipartFile file) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        if (dto.getClassId()==null||0L==dto.getClassId()) {
            dto.setRole(UserInforCore.ROLE_TEACHER);
        }
        else {
            dto.setRole(UserInforCore.ROLE_STUDENT);
        }
//        if (dto.getProfessionalId()==null||0L==dto.getProfessionalId()) {
//            result = new HashMap<>();
//            result.put(ApiReturnConstants.SUCCESS, false);
//            result.put(ApiReturnConstants.ERROR, "专业Id不能为空！");
//            return new ResponseEntity(result, HttpStatus.OK);
//        }
        List<AccountDTO> list=null;
		try {
			 list = userService.fileTransformList(file, dto);
		} catch (Exception e) {
			result.put(ApiReturnConstants.SUCCESS,false);
			result.put(ApiReturnConstants.MESSAGE,e.getMessage());
			return new ResponseEntity(result, HttpStatus.OK);
		}
        result = userService.addAccount(list);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/edituser", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "PUT", value = "修改用户信息", response = Void.class, notes = "修改用户信息<br>@author zhengning")
    public ResponseEntity<?> editUser(@RequestHeader("Authorization") String token,
                                      @ApiParam(value = "id:用户id必填,jobNum:学号/工号（老师学生必填），collegeId:院系id（老师学生必填），professionalId(专业id)和classId(班级id)为学生必填，username:账号（管理员必填），账号默认密码为dingli123", required = false) @RequestBody AccountDTO dto) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        Map<String, Object> result = userService.editAccount(dto);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/disableuser", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "停用/启用用户账号", response = Void.class, notes = "停用/启用用户账号<br>@author zhengning")
    public ResponseEntity<?> disableUser(@RequestHeader("Authorization") String token,
                                         @ApiParam(value = "用户id", required = false) @RequestParam(value = "userId", required = true) Long userId,
                                         @ApiParam(value = "用户账号状态，0（启用）2（停用）", required = false) @RequestParam(value = "status", required = true) Integer status) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        Map<String, Object> result = userService.disableAccount(userId, status);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/getuser", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "根据用户id查询用户信息", response = Void.class, notes = "根据用户id查询用户信息<br>@author zhengning")
    public ResponseEntity<?> getUser(@RequestHeader("Authorization") String token,
                                     @ApiParam(value = "用户id", required = false) @RequestParam(value = "userId", required = true) Long userId) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        Map<String, Object> result = userService.getAccount(userId);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/findpage", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "用户信息分页查询", response = Void.class, notes = "用户信息分页查询<br>@author zhengning")
    public ResponseEntity<?> findPage(@RequestHeader("Authorization") String token,
                                      @ApiParam(value = "role:角色（admin,teacher,student）必填", required = false) @RequestBody QueryUserDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        Map<String, Object> result = null;
        if (StringUtils.isEmpty(domain.getRole())) {
            result = new HashMap<>();
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "查询用户信息缺少角色！");
        } else {
            if (UserInforCore.ROLE_TEACHER.equals(domain.getRole())) {
                result = userService.findTeacherPage(domain);
            } else if (UserInforCore.ROLE_STUDENT.equals(domain.getRole())) {
                result = userService.findStudentPage(domain);
            } else {
                result = userService.findAdminPage(domain);
            }
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }

}
